package com.ebai.product.management.service.system;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ebai.product.management.base.cache.service.MessageCacheImpl;
import com.ebai.product.management.model.entity.RoleUser;
import com.ebai.product.management.repository.system.RoleUserRepository;

@Service
public class RoleUserService {
	
	@Autowired
	private RoleUserRepository roleUserRepository;

	/**
	 * 角色授权给人员-单角色多人员
	 * @param rolePid
	 * @param userids
	 * @return
	 */
	public Map<String, Object> saveRoleUsersData(String rolePid, String userids) {
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("success", Boolean.FALSE);

        try {
        	String[] useridArr = userids.split(",");
        	RoleUser roleUser = null;
        	List<RoleUser> roleUserList = new ArrayList<RoleUser>();
        	for (int i = 0; i < useridArr.length; i++) {
        		roleUser = new RoleUser();
        		roleUser.setRolePid(rolePid);
        		roleUser.setUserPid(useridArr[i]);
        		
        		roleUserList.add(roleUser);
			}
        	// 先删除
        	roleUserRepository.deleteUserRoleByRoleid(rolePid);
        	// 后插入
        	roleUserRepository.saveAll(roleUserList);
        	
            result.put("success", Boolean.TRUE);
            result.put("msg", MessageCacheImpl.getMsg("Global.SaveData.Message.Success"));
        }
        catch (Exception e) {
            e.printStackTrace();
            result.put("msg", MessageCacheImpl.getMsg("Global.SaveData.Message.Failure") + e.getMessage());
        }

        return result;
    }
	
	/**
	 * 人员授权角色-》单人员多角色
	 * @param rolePids
	 * @param userPid
	 * @return
	 */
	public Map<String, Object> saveUserRolesData(String rolePids, String userPid) {
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("success", Boolean.FALSE);

        try {
        	String[] roleidArr = rolePids.split(",");
        	RoleUser roleUser = null;
        	List<RoleUser> roleUserList = new ArrayList<RoleUser>();
        	for (int i = 0; i < roleidArr.length; i++) {
        		roleUser = new RoleUser();
        		roleUser.setRolePid(roleidArr[i]);
        		roleUser.setUserPid(userPid);
        		
        		roleUserList.add(roleUser);
			}
        	// 先删除
        	roleUserRepository.deleteUserRoleByUserid(userPid);
        	// 后插入
        	roleUserRepository.saveAll(roleUserList);
        	
            result.put("success", Boolean.TRUE);
            result.put("msg", MessageCacheImpl.getMsg("Global.SaveData.Message.Success"));
        }
        catch (Exception e) {
            e.printStackTrace();
            result.put("msg", MessageCacheImpl.getMsg("Global.SaveData.Message.Failure") + e.getMessage());
        }

        return result;
    }
}
